package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.mapper.MenuMapper;
import com.itheima.health.pojo.Menu;
import com.itheima.health.service.MenuService;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.MenuVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Reference
    private UserService userService;


    @Override
    public List<MenuVO> getUsername(String userName) {
        //根据用户名获取 角色id集合
        List<Integer> roleIds = userService.getRoleIdsByUserName(userName);
        Map<Integer,MenuVO> map = new HashMap<>();
        for (Integer roleId : roleIds) {
            List<MenuVO> parentMenu = baseMapper.getParentMenu(roleId);
            for (MenuVO menu : parentMenu) {
                if (!map.containsKey(menu.getId())){
                    map.put(menu.getId(),menu);
                }else {
                    menu = map.get(menu.getId());
                }
                Set<MenuVO> parent = menu.getChildren();
                List<MenuVO> childrenMenu = baseMapper.getChildrenByParentMenuId(menu.getId(), roleId);
                for (MenuVO menuVO : childrenMenu) {
                    String linkUrl = menuVO.getLinkUrl();
                    if(!StringUtils.isBlank(linkUrl)){
                        String substring = linkUrl.substring(0, linkUrl.indexOf("."));

                        menuVO.setLinkUrl(substring);
                    }
                    parent.add(menuVO);
                }
            }
        }
        List<MenuVO> menuVOS = new ArrayList<>(map.values());
        return menuVOS;
    }

}
